package com.mayisoftware.mayioa.common.impl.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

/**
 * 上传SVN工具类
 */
public class KeepUtil {
    /**
     * 日志对象
     */
    private final static Logger logger = LoggerFactory.getLogger(KeepUtil.class);

    /**
     * 空目录添加内容
     */
    public static final String packageFile = ".keep";

    /**
     * 提交代码前，给空目录添加.keep文件
     * @param args
     */
//    public static void main(String[] args) {
//        String path = getRealPath();
//        File file = new File(path);
//        try {
//            traversalAllFolder(file);
//        } catch (Exception e) {
//            logger.error("发生异常{}",e);
//        }
//    }

    /**
     * 遍历当前文件夹下的所有文件夹，对空的文件夹创建.keep文件
     *
     * @param dir
     * @throws Exception
     */
    final static void traversalAllFolder(File dir) throws Exception {
        File[] fs = dir.listFiles();
        int fsLength = fs.length;
        if (fsLength == 0) {
            createFile(dir.getAbsolutePath());
        } else {
            for (int i = 0; i < fsLength; i++) {
                if (fs[i].isDirectory()) {
                    try {
                        traversalAllFolder(fs[i]);
                    } catch (Exception e) {
                        logger.error("发生异常{}",e);
                    }
                }
            }
        }
    }

    /**
     * 创建.keep文件
     *
     * @param folderPath
     *            路径名
     */
    public static void createFile(String folderPath) {
        String fileName = folderPath + "/" + packageFile;
        File file = new File(fileName);
        try {
            file.createNewFile();
        } catch (IOException e) {
            logger.error("发生异常{}",e);
        }
    }

    /**
     * 获取当前jar包所在路径
     *
     * @return
     */
    public static String getRealPath() {
        String realPath = KeepUtil.class.getClassLoader().getResource("")
                .getFile();
        java.io.File file = new java.io.File(realPath);
        realPath = file.getParentFile().getParentFile().getParentFile().getAbsolutePath();
        try {
            realPath = java.net.URLDecoder.decode(realPath, "utf-8");
        } catch (Exception e) {
            logger.error("发生异常{}",e);
        }

        return realPath;
    }

}
